package wang.chunfan.springcloud.learning.zuul.proxy.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @version 1.0
 * @Author wangchunfan
 * @Date 2020/5/24 14:52
 * @Description 打印日志的前置过滤器
 **/
@Component
public class PreLogFilter extends ZuulFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(PreLogFilter.class);

    /**
     * 过滤器类型，共 4 种：pre routing post error
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器执行顺序，数值越小的先执行
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否进行过滤，true 是
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 自定义的过滤逻辑
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String remoteHost = request.getRemoteHost();
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        LOGGER.info("Remote host: {}, method: {}, uri: {}", remoteHost, method, requestURI);
        return null;
    }
}
